<?php

class joinPay2 {

  var $payment_conf = array();

  var $member = array();

  function __construct(){
    $payment = Model("mb_payment")->getMbPaymentOpenInfo(["payment_code" => "joinpay2"]);
    $this->paymentConf = $payment['payment_config'];
    $this->member = get_mobile_member_info();
  }

  function mobile_get_code(){

    $url = "https://www.joinpay.com/trade/uniPayApi.action";

    $orderInfo = Model()->table('order')->where([
      'order_state' => ORDER_STATE_NEW,
      'buyer_id' => $this->member["member_id"],
      'pay_sn'   => $_REQUEST['pay_sn']
    ])->find();

    $orderGoods = Model()->table("order_goods")->where([
      'buyer_id' => $this->member["member_id"],
      'order_id' => $orderInfo['order_id']
    ])->find();

    $params = array(
      "p0_Version" => "1.0",
      "p1_MerchantNo" => $this->paymentConf["merchantNo"],
      "p2_OrderNo"    => $orderInfo["order_sn"],
      "p3_Amount"     => $orderInfo["order_amount"],
      "p4_Cur"        => 1,
      "p5_ProductName"=> $orderGoods['goods_name'],
      "p9_NotifyUrl"  => SHOP_DOMAIN . "/mobile/api/payment/joinpay2/notify_url.php",
      "q1_FrpCode"    => "WEIXIN_GZH",
      "q5_OpenId"     => $_REQUEST['openid'],
      "q7_AppId"      => $this->paymentConf["appId"]
    );
    $params['hmac'] = $this->joinpay_sign($params);

    $res = $this->request($url, $params);

    // 海关实时请求数据
    if($orderInfo["is_tax_order"]){
      $info = Model()->table("pay_exchange_info")->find([
        "order_sn"=>$orderInfo["order_sn"]
      ]);
      if($info){
        $data = array();
        $data["ebpCode"] = "4403160CTP";
        $data["payCode"] = "440196T002";
        $data["initalRequest"] = json_encode($params);
        $data["recpAccount"] = "888105600009620";
        $data["recpCode"] = "4403160CTP";
        $data["recpName"] = "深圳市明易科技有限公司";
        Model()->table("pay_exchange_info")
          ->where([
            "orderNo" => $orderInfo["order_sn"]
          ])
          ->update($data);
      }else{
        $data = array();
        $data["orderNo"] = $orderInfo["order_sn"];
        $data["totalAmount"] = $orderInfo["order_amount"];
        $data["ebpCode"] = "4403160CTP";
        $data["payCode"] = "440196T002";
        $data["currency"] = "142";
        $data["initalRequest"] = json_encode($params);
        $data["recpAccount"] = "888105600009620";
        $data["recpCode"] = "4403160CTP";
        $data["recpName"] = "深圳市明易科技有限公司";
        Model()->table("pay_exchange_info")->insert($data);
      }
    }


    return $res;
  }

  public function getNotifyInfo($payment_config){
    //将系统的控制参数置空，防止因为加密验证出错
    unset($_GET['act']);
    unset($_GET['op']);
    unset($_GET['payment_code']);

    $server_hmac = $_GET["hmac"];
    $resBody = json_encode($_GET);
    unset($_GET['hmac']);

    $merchantkey = $payment_config["merchantKey"];
    ksort($_GET);
    foreach($_GET as $key => $val){
      $_GET[$key] = urldecode($val);
    }
    $str = implode('',$_GET);
    $str .= $merchantkey;
    $client_hmac = md5($str);
    $order_info = Model()->table('order')->where(array('order_sn' => $_GET['r2_OrderNo']))->find();
    if($client_hmac === $server_hmac) {

      $verDept = '3';
      if($_GET["rf_ChannelCode"] == "UNION"){
        $verDept = "1";
      }else if($_GET["rf_ChannelCode"] == "NUCC"){
        $verDept = "2";
      }
      $tradingTime = date("YmdHis", strtotime(urldecode(urldecode($_GET["ra_PayTime"]))));

      Model()->table("pay_exchange_info")
      ->where([
        "orderNo" => $_GET['r2_OrderNo']
      ])
      ->update([
        "verDept" => $verDept,
        "payTransactionId"=> $_GET['r9_BankTrxNo'],
        "initalResponse" => $resBody,
        "tradingTime" => $tradingTime
      ]);

      return array(
        //商户订单号
        'out_trade_no' => $order_info["pay_sn"],
        //支付宝交易号
        'trade_no' => $_GET['r9_BankTrxNo'],
      );
    }
    return false;
  }

  private function joinpay_sign($params){
    $merchantkey = $this->paymentConf["merchantKey"];
    ksort($params);
    $str = implode('',$params);
    $str .= $merchantkey;
    return md5($str);
  }

  private function request($url, $param, $decode = true){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    if ($decode) {
      return json_decode($response,true);
    }else{
      return $response;
    }
  }

}

